package edu.hziee.controller;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/login")
public class LoginController {
	
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView get(){
		return new ModelAndView("login/login");
	}
		
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView post(HttpSession session,
			HttpServletRequest req,@RequestParam String userName,
			@RequestParam String password,
			@RequestParam(required=false) String returnUrl){
		
		Connection con;
		String driver="com.mysql.jdbc.Driver";
	
		String url="jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8";
	
		
		
			try {
				Class.forName(driver);
				con=DriverManager.getConnection(url,"root","123456");
				Statement stat=con.createStatement();
				ResultSet rs=stat.executeQuery("select * from users");
				while(rs.next()){
					if(userName.equals(rs.getString(1)) && password.equals(rs.getString(2))){
						session.setAttribute("userName", userName);
						if(returnUrl == null)
							return new ModelAndView("redirect:" +returnUrl.replace(req.getContextPath(),""));
						else
							return new ModelAndView("redirect:book");
					}
				}
				
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			ModelAndView mav = new ModelAndView("/login/login");
			mav.addObject("error","用户名或密码错误");
			return mav;
	
	}

}
